// Packet.cpp: implementation of the CPacket class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
//#include "Server.h"
#include "Packet.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

Packet::Packet():
	m_dwId(0),
	m_dwDataSize(0),
	m_lpbyData(NULL)
{
	m_time = CTime::GetCurrentTime();
}

Packet::Packet(DWORD dwDataSize):
	m_dwId(0),
	m_dwDataSize(0),
	m_lpbyData(NULL)
{
	Alloc(dwDataSize);
	memset(m_lpbyData, 0, m_dwDataSize);
	m_time = CTime::GetCurrentTime();
}

Packet::Packet(DWORD dwDataSize, LPBYTE lpbyData):
	m_dwId(0),
	m_dwDataSize(0),
	m_lpbyData(NULL)
{
	Alloc(dwDataSize);
	memcpy(m_lpbyData, lpbyData, m_dwDataSize);
	m_time = CTime::GetCurrentTime();
}

Packet::~Packet()
{
	Free();
}

void Packet::Alloc(DWORD dwAlloc)
{
	Free();
	if (dwAlloc != 0) m_dwDataSize = dwAlloc;
	m_lpbyData = new BYTE[m_dwDataSize];
}

void Packet::Free()
{
	if (m_lpbyData) delete m_lpbyData;
	m_lpbyData = NULL;
}

void Packet::Serialize(CArchive& ar)
{
	if (ar.IsStoring())
	{
		ar << m_dwId << m_dwDataSize;
		for (DWORD dw = 0;dw < m_dwDataSize;dw++)
		{
			ar << m_lpbyData[dw];
		}
	}
	else
	{
		ar >> m_dwId >> m_dwDataSize;
		Alloc();
		for (DWORD dw = 0;dw < m_dwDataSize;dw++)
		{
			ar >> m_lpbyData[dw];
		}
	}
}

const Packet& Packet::operator =(const Packet& rhs)
{
	Free();

	Alloc(rhs.m_dwDataSize);
	m_dwId = rhs.m_dwId;
	memcpy(m_lpbyData, rhs.m_lpbyData, rhs.m_dwDataSize);

	return *this;
}